<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI选股系统 - K线图</title>
    <script src="/static/lib/js/vue.global.prod.js"></script>
    <script src="/static/lib/js/axios.min.js"></script>
    <!-- 引入 klinecharts 库 -->
    <script src="/static/lib/js/klinecharts.min.js"></script>
    <link href="/static/lib/css/all.min.css" rel="stylesheet">
    <link href="/static/base.css" rel="stylesheet">
    <link href="/static/components.css" rel="stylesheet">
    <link href="/static/pages.css" rel="stylesheet">
    <link href="/static/utilities.css" rel="stylesheet">
    <style>
        /* 支撑位和压力位样式 */
        .support-resistance-info {
            margin-top: 20px;
            padding: 15px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 8px;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .levels-container {
            display: flex;
            gap: 30px;
            justify-content: center;
        }
        
        .level-group {
            flex: 1;
            max-width: 200px;
        }
        
        .level-group h4 {
            margin: 0 0 10px 0;
            font-size: 14px;
            font-weight: 600;
            text-align: center;
        }
        
        .level-list {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        
        .level-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 12px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 6px;
            border-left: 3px solid;
        }
        
        .level-item:nth-child(1) {
            border-left-color: #FF5722;
        }
        
        .level-item:nth-child(2) {
            border-left-color: #FF9800;
        }
        
        .level-item:nth-child(3) {
            border-left-color: #FFC107;
        }
        
        .level-price {
            font-weight: 600;
            font-size: 14px;
        }
        
        .level-strength {
            font-size: 12px;
            opacity: 0.8;
        }
        
        /* K线图表容器样式 */
        .chart-container {
            width: 100%;
            height: 500px;
            position: relative;
            border: 2px solid #ddd;
            background-color: #f9f9f9;
        }
        
        #klineChart {
            width: 100%;
            height: 100%;
            min-height: 400px;
        }
        
        #volumeChart {
            width: 100%;
            height: 100%;
            min-height: 150px;
        }
        
        .volume-chart-container {
            width: 100%;
            height: 200px;
            margin-top: 20px;
        }
        
        /* K线图A股颜色设置 */
        :root {
            --kline-up-color: #FF4444;      /* 上涨K线颜色（红色） */
            --kline-down-color: #00C851;    /* 下跌K线颜色（绿色） */
            --kline-nochange-color: #999999; /* 平盘K线颜色（灰色） */
        }
        
        /* 强制设置K线图颜色 */
        #klineChart canvas {
            --kline-up-color: #FF4444 !important;
            --kline-down-color: #00C851 !important;
            --kline-nochange-color: #999999 !important;
        }
        
        #volumeChart canvas {
            --kline-up-color: #FF4444 !important;
            --kline-down-color: #00C851 !important;
            --kline-nochange-color: #999999 !important;
        }
        
        /* 直接覆盖K线图颜色 */
        #klineChart svg rect[fill*="green"], #klineChart svg rect[fill*="00C851"] {
            fill: #FF4444 !important;
        }
        
        #klineChart svg rect[fill*="red"], #klineChart svg rect[fill*="FF4444"] {
            fill: #FF4444 !important;
        }
        
        /* 成交量颜色覆盖 */
        #volumeChart svg rect[fill*="green"], #volumeChart svg rect[fill*="00C851"] {
            fill: #FF4444 !important;
        }
        
        #volumeChart svg rect[fill*="red"], #volumeChart svg rect[fill*="FF4444"] {
            fill: #FF4444 !important;
        }
        
                 /* 响应式设计 */
         @media (max-width: 768px) {
             .levels-container {
                 flex-direction: column;
                 gap: 15px;
             }
             
             .level-group {
                 max-width: none;
             }
            
            .chart-container {
                height: 400px;
            }
            
            .volume-chart-container {
                height: 150px;
             }
         }
     </style>
</head>
<body>
    <div id="app">
        <div class="app-container">
            <!-- 头部 -->
            <div class="header">
                <div class="header-nav">
                    <h1><i class="fas fa-chart-line"></i> K线图分析</h1>
                    <div class="header-nav-links">
                        <a href="/" class="header-nav-link home">
                            <i class="fas fa-home"></i> 专业版
                        </a>
                        <a href="/performance" class="header-nav-link performance">
                            <i class="fas fa-chart-line"></i> 收益分析
                        </a>
                        <a href="/admin/imps" class="header-nav-link import">
                            <i class="fas fa-database"></i> 数据导入
                        </a>
                        <a href="/news" class="header-nav-link news">
                            <i class="fas fa-newspaper"></i> 新闻中心
                        </a>
                        <a href="/fundamental" class="header-nav-link news">
                            <i class="fas fa-chart-bar"></i> 基本面信息
                        </a>
                    </div>
                </div>
                <p>查看股票的历史价格走势和技术指标</p>
                <div class="header-stats" v-if="stockStats">
                    <div class="stat-item">
                        <div class="stat-number">{{ stockStats.totalDays }}</div>
                        <div class="stat-label">数据天数</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number">{{ stockStats.latestPrice }}</div>
                        <div class="stat-label">最新价格</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number" :class="stockStats.totalChange >= 0 ? 'positive' : 'negative'">
                            {{ stockStats.totalChange >= 0 ? '+' : '' }}{{ stockStats.totalChange }}%
                        </div>
                        <div class="stat-label">总涨跌幅</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number">{{ stockStats.avgVolume }}</div>
                        <div class="stat-label">平均成交量</div>
                    </div>
                </div>
                
                <!-- 支撑位和压力位信息 -->
                <div class="support-resistance-info" v-if="showSupportResistance && supportResistanceLevels">
                    <div class="levels-container">
                        <div class="level-group">
                            <h4><i class="fas fa-arrow-up" style="color: #F44336;"></i> 压力位</h4>
                            <div class="level-list">
                                <div v-for="(level, index) in supportResistanceLevels.resistance" :key="'resistance-' + index" class="level-item">
                                    <span class="level-price">{{ level.price.toFixed(2) }}</span>
                                    <span class="level-strength">强度: {{ level.strength }}</span>
                                </div>
                            </div>
                        </div>
                        <div class="level-group">
                            <h4><i class="fas fa-arrow-down" style="color: #4CAF50;"></i> 支撑位</h4>
                            <div class="level-list">
                                <div v-for="(level, index) in supportResistanceLevels.support" :key="'support-' + index" class="level-item">
                                    <span class="level-price">{{ level.price.toFixed(2) }}</span>
                                    <span class="level-strength">强度: {{ level.strength }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 主内容区域 -->
            <div class="main-content">
                <div class="kline-page-content">
                    <!-- 控制面板 -->
                    <div class="control-panel panel kline-control-panel">
                        <div class="panel-title">
                            <i class="fas fa-cog"></i>
                            图表设置
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">显示天数</label>
                            <select v-model="displayDays" @change="loadStockData" class="form-control">
                                <option value="30">30天</option>
                                <option value="60">60天</option>
                                <option value="90">90天</option>
                                <option value="120">120天</option>
                                <option value="250">250天</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">技术指标</label>
                            <div class="checkbox-group">
                                <label class="checkbox-label">
                                    <input type="checkbox" v-model="showMA5" @change="updateChart">
                                    <span class="checkmark"></span>
                                    MA5
                                </label>
                                <label class="checkbox-label">
                                    <input type="checkbox" v-model="showMA10" @change="updateChart">
                                    <span class="checkmark"></span>
                                    MA10
                                </label>
                                <label class="checkbox-label">
                                    <input type="checkbox" v-model="showMA20" @change="updateChart">
                                    <span class="checkmark"></span>
                                    MA20
                                </label>
                                <label class="checkbox-label">
                                    <input type="checkbox" v-model="showVolume" @change="updateChart">
                                    <span class="checkmark"></span>
                                    成交量
                                </label>
                                <label class="checkbox-label">
                                    <input type="checkbox" v-model="showSupportResistance" @change="updateChart">
                                    <span class="checkmark"></span>
                                    支撑压力位
                                </label>
                            </div>
                        </div>
                        
                        <button @click="loadStockData" :disabled="loading" class="btn btn-primary">
                            <i v-if="loading" class="fas fa-spinner fa-spin"></i>
                            <i v-else class="fas fa-sync-alt"></i>
                            {{ loading ? '加载中...' : '刷新数据' }}
                        </button>
                        
                        <div v-if="message" class="alert" :class="'alert-' + messageType">
                            <i :class="getStatusIcon()"></i>
                            {{ message }}
                        </div>
                    </div>

                    <!-- 图表区域 -->
                    <div class="chart-panel panel">
                        <div class="panel-title">
                            <i class="fas fa-chart-area"></i>
                            K线图表
                        </div>
                        
                        <div class="chart-content">
                            <div v-if="loading" class="loading">
                                <i class="fas fa-spinner fa-spin"></i> 正在加载K线数据，请稍候...
                            </div>
                            
                            <div v-else-if="stockData.length === 0" class="no-data">
                                <i class="fas fa-chart-line"></i>
                                <p>暂无K线数据</p>
                            </div>
                            
                            <div v-else class="chart-container">
                                <div id="klineChart"></div>
                            </div>
                            
                            <!-- 成交量图表 -->
                            <div v-if="showVolume && stockData.length > 0" class="volume-chart-container">
                                <div id="volumeChart"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        const { createApp } = Vue;
        
        createApp({
            data() {
                return {
                    stockInfo: {
                        securityId: '',
                        securityName: ''
                    },
                    stockData: [],
                    stockStats: null,
                    displayDays: 60,
                    showMA5: true,
                    showMA10: true,
                    showMA20: false,
                    showVolume: true,
                    showSupportResistance: true,
                    supportResistanceLevels: null,
                    loading: false,
                    message: '',
                    messageType: 'success',
                    klineChart: null,
                    volumeChart: null
                }
            },
            
            async mounted() {
                // 等待 klinecharts 加载完成
                await this.waitForKlinecharts();
                
                this.parseUrlParams();
                await this.loadStockData();
            },
            
            methods: {
                async waitForKlinecharts() {
                    // 等待 klinecharts 加载完成
                    let attempts = 0;
                    const maxAttempts = 50; // 最多等待5秒
                    
                    while (typeof window.klinecharts === 'undefined' && attempts < maxAttempts) {
                        await new Promise(resolve => setTimeout(resolve, 100));
                        attempts++;
                    }
                    
                    if (typeof window.klinecharts === 'undefined') {
                        console.error('klinecharts 加载超时');
                        this.showMessage('图表库加载失败，请刷新页面重试', 'error');
                    } else {

                    }
                },
                
                parseUrlParams() {
                    const urlParams = new URLSearchParams(window.location.search);
                    this.stockInfo.securityId = urlParams.get('id') || '';
                    this.stockInfo.securityName = urlParams.get('name') || this.stockInfo.securityId;
                    
                    if (!this.stockInfo.securityId) {
                        this.showMessage('缺少股票代码参数', 'error');
                        return;
                    }
                },
                
                async loadStockData() {
                    this.loading = true;
                    this.message = '';
                    
                    try {
                        const response = await axios.get(`/api/stock-kline/${this.stockInfo.securityId}?limit=${this.displayDays}`);
                        if (response.data.success) {
                            this.stockData = response.data.data.kline_data || [];
                            this.calculateStats();
                            this.$nextTick(() => {
                                this.renderChart();
                            });
                        } else {
                            this.showMessage(response.data.error, 'error');
                        }
                    } catch (error) {
                        this.showMessage('加载K线数据失败: ' + error.message, 'error');
                    } finally {
                        this.loading = false;
                    }
                },
                
                calculateStats() {
                    if (this.stockData.length === 0) {
                        this.stockStats = null;
                        this.supportResistanceLevels = null;
                        return;
                    }
                    
                    const firstPrice = parseFloat(this.stockData[0].close) || 0;
                    const lastPrice = parseFloat(this.stockData[this.stockData.length - 1].close) || 0;
                    const totalChange = firstPrice > 0 ? ((lastPrice - firstPrice) / firstPrice * 100) : 0;
                    const avgVolume = this.stockData.reduce((sum, item) => sum + (parseFloat(item.volume) || 0), 0) / this.stockData.length;
                    
                    this.stockStats = {
                        totalDays: this.stockData.length,
                        latestPrice: lastPrice.toFixed(2),
                        totalChange: totalChange.toFixed(2),
                        avgVolume: this.formatVolume(avgVolume)
                    };
                    
                    // 计算支撑位和压力位
                    if (this.showSupportResistance) {
                        this.supportResistanceLevels = this.calculateSupportResistance();
                    }
                },
                
                formatVolume(volume) {
                    if (volume >= 100000000) {
                        return (volume / 100000000).toFixed(1) + '亿';
                    } else if (volume >= 10000) {
                        return (volume / 10000).toFixed(1) + '万';
                    } else {
                        return Math.round(volume).toString();
                    }
                },
                
                renderChart() {
                    if (this.stockData.length === 0 || this.loading) {
                        return;
                    }
                    
                    // 确保在下一个DOM更新周期执行
                    this.$nextTick(() => {
                        setTimeout(() => {
                            try {
                                this.renderMainChart();
                                
                                if (this.showVolume && this.stockData.length > 0) {
                                    this.renderVolumeChart();
                                }
                            } catch (error) {
                                console.error('渲染图表时出错:', error);
                                this.showMessage('图表渲染失败: ' + error.message, 'error');
                            }
                        }, 50);
                    });
                },
                
                renderMainChart() {
                    if (typeof window.klinecharts === 'undefined') {
                        console.error('klinecharts 未定义，无法渲染图表');
                        this.showMessage('图表库未加载，请刷新页面重试', 'error');
                        return;
                    }
                    
                    // 尝试设置全局K线图颜色配置
                    try {
                        if (window.klinecharts.setStyles) {
                            window.klinecharts.setStyles({
                                candle: {
                                    up: { color: '#FF4444' },
                                    down: { color: '#00C851' },
                                    noChange: { color: '#999999' }
                                }
                            });
                        }
                    } catch (e) {
                        console.log('设置全局K线图颜色失败:', e);
                    }
                    
                    const container = document.getElementById('klineChart');
                    if (!container) {
                        console.error('K线图表容器未找到');
                        return;
                    }
                    
                    try {
                        // 销毁之前的图表
                        if (this.klineChart) {
                            const disposeMethods = [
                                'dispose',
                                'destroy',
                                'remove',
                                'clear',
                                'reset'
                            ];
                            
                            let disposeMethodFound = false;
                            
                            for (const method of disposeMethods) {
                                if (typeof this.klineChart[method] === 'function') {
                                    try {
                                        this.klineChart[method]();
                                        console.log(`使用 ${method} 方法销毁K线图表`);
                                        disposeMethodFound = true;
                                        break;
                                    } catch (error) {
                                        console.log(`销毁K线图表失败 (${method}):`, error);
                                    }
                                }
                            }
                            
                            if (!disposeMethodFound) {
                                console.log('未找到可用的销毁方法，跳过销毁');
                            }
                        }
                        
                        // 创建新的K线图表
                        console.log('开始创建K线图表，容器:', container);
                        console.log('klinecharts对象:', window.klinecharts);
                        console.log('init方法:', typeof window.klinecharts.init);
                        
                        try {
                            // 尝试不同的初始化方法，并传入A股颜色配置
                            const chartOptions = {
                                styles: {
                                    candle: {
                                        up: {
                                            color: '#FF4444',      // 上涨K线颜色（红色）
                                            borderColor: '#FF4444', // 上涨K线边框颜色
                                            wickColor: '#FF4444'    // 上涨K线影线颜色
                                        },
                                        down: {
                                            color: '#00C851',      // 下跌K线颜色（绿色）
                                            borderColor: '#00C851', // 下跌K线边框颜色
                                            wickColor: '#00C851'    // 下跌K线影线颜色
                                        },
                                        noChange: {
                                            color: '#999999',      // 平盘K线颜色（灰色）
                                            borderColor: '#999999', // 平盘K线边框颜色
                                            wickColor: '#999999'    // 平盘K线影线颜色
                                        }
                                    }
                                }
                            };
                            
                            if (typeof window.klinecharts.init === 'function') {
                                this.klineChart = window.klinecharts.init(container, chartOptions);
                            } else if (typeof window.klinecharts.create === 'function') {
                                this.klineChart = window.klinecharts.create(container, chartOptions);
                            } else if (typeof window.klinecharts === 'function') {
                                this.klineChart = window.klinecharts(container, chartOptions);
                            } else {
                                throw new Error('找不到可用的klinecharts初始化方法');
                            }
                            console.log('K线图表创建成功:', this.klineChart);
                        } catch (error) {
                            console.error('创建K线图表失败:', error);
                            this.showMessage('创建图表失败: ' + error.message, 'error');
                            return;
                        }
                        
                        // 转换数据格式为 klinecharts 需要的格式，添加涨跌标记
                        const klineData = this.stockData.map(item => {
                            const close = parseFloat(item.close) || 0;
                            const open = parseFloat(item.open) || 0;
                            const volume = parseFloat(item.volume) || 0;
                            
                            // 计算涨跌，用于颜色判断
                            const isUp = close > open;
                            const isDown = close < open;
                            
                            return {
                                timestamp: new Date(item.date).getTime(),
                                open: open,
                                high: parseFloat(item.high) || 0,
                                low: parseFloat(item.low) || 0,
                                close: close,
                                volume: volume,
                                // 添加涨跌标记，用于K线颜色显示
                                trend: isUp ? 'up' : isDown ? 'down' : 'noChange',
                                // 强制设置颜色属性
                                color: isUp ? '#FF4444' : isDown ? '#00C851' : '#999999'
                            };
                        });
                        
                        console.log('转换后的K线数据:', klineData.slice(0, 3));
                        console.log('数据长度:', klineData.length);
                        console.log('第一个数据点:', klineData[0]);
                        console.log('最后一个数据点:', klineData[klineData.length - 1]);
                        
                        // 设置数据
                        console.log('开始设置K线数据...');
                        
                        // 尝试不同的数据设置方法
                        const dataMethods = ['applyNewData', 'setData', 'loadData', 'updateData', 'addData'];
                        let dataMethodFound = false;
                        
                        for (const method of dataMethods) {
                            if (typeof this.klineChart[method] === 'function') {
                                try {
                                    if (method === 'addData') {
                                        // addData方法可能需要不同的参数格式
                                        this.klineChart[method](klineData, true);
                                    } else {
                                        this.klineChart[method](klineData);
                                    }
                                    console.log(`使用 ${method} 方法设置数据成功`);
                                    dataMethodFound = true;
                                    break;
                        } catch (error) {
                                    console.log(`${method} 方法失败:`, error);
                                }
                            }
                        }
                        
                        if (!dataMethodFound) {
                            console.error('未找到可用的数据设置方法');
                            console.log('可用的方法:', Object.getOwnPropertyNames(this.klineChart));
                            this.showMessage('图表数据设置失败', 'error');
                        }
                        
                        console.log('K线数据设置完成');
                        
                        // 添加技术指标
                        this.addTechnicalIndicators();
                        
                        // 添加支撑位和压力位
                        if (this.showSupportResistance) {
                            this.addSupportResistanceLevels();
                        }
                        
                        // 设置图表样式 - A股习惯：红涨绿跌
                        try {
                            // 方法1：使用setStyles
                            this.klineChart.setStyles({
                                grid: {
                                    show: true,
                                    horizontal: {
                                        show: true,
                                        color: '#EDEDED',
                                        size: 1
                                    },
                                    vertical: {
                                        show: true,
                                        color: '#EDEDED',
                                        size: 1
                                    }
                                },
                                candle: {
                                    // A股习惯：红涨绿跌 - 使用正确的属性名
                                    up: {
                                        color: '#FF4444',      // 上涨K线颜色（红色）
                                        borderColor: '#FF4444', // 上涨K线边框颜色
                                        wickColor: '#FF4444'    // 上涨K线影线颜色
                                    },
                                    down: {
                                        color: '#00C851',      // 下跌K线颜色（绿色）
                                        borderColor: '#00C851', // 下跌K线边框颜色
                                        wickColor: '#00C851'    // 下跌K线影线颜色
                                    },
                                    noChange: {
                                        color: '#999999',      // 平盘K线颜色（灰色）
                                        borderColor: '#999999', // 平盘K线边框颜色
                                        wickColor: '#999999'    // 平盘K线影线颜色
                                    },
                                    priceMark: {
                                        show: true,
                                        high: {
                                            show: true,
                                            color: '#D9D9D9',
                                            backgroundColor: '#FF4444'  // 最高价标记改为红色
                                        },
                                        low: {
                                            show: true,
                                            color: '#D9D9D9',
                                            backgroundColor: '#00C851'  // 最低价标记改为绿色
                                        }
                                    }
                                }
                            });
                        } catch (e) {
                            console.log('setStyles方法失败:', e);
                        }
                        
                        // 方法2：尝试使用其他可能的配置方法
                        try {
                            if (this.klineChart.updateStyles) {
                                this.klineChart.updateStyles({
                                    candle: {
                                        up: { color: '#FF4444' },
                                        down: { color: '#00C851' },
                                        noChange: { color: '#999999' }
                                    }
                                });
                            }
                        } catch (e) {
                            console.log('updateStyles方法失败:', e);
                        }
                        
                        // 方法3：强制设置DOM元素的颜色
                        setTimeout(() => {
                            try {
                                const chartContainer = document.getElementById('klineChart');
                                if (chartContainer) {
                                    const svgElements = chartContainer.querySelectorAll('svg rect, svg path');
                                    svgElements.forEach(el => {
                                        const fill = el.getAttribute('fill');
                                        if (fill && fill.includes('00C851')) {
                                            el.setAttribute('fill', '#FF4444');
                                        }
                                    });
                                }
                            } catch (e) {
                                console.log('强制设置DOM颜色失败:', e);
                            }
                        }, 1000);
                        
                        // 方法4：持续监控和强制设置颜色（每500ms检查一次）
                        const colorMonitor = setInterval(() => {
                            try {
                                const chartContainer = document.getElementById('klineChart');
                                if (chartContainer) {
                                    let colorChanged = false;
                                    const svgElements = chartContainer.querySelectorAll('svg rect, svg path');
                                    svgElements.forEach(el => {
                                        const fill = el.getAttribute('fill');
                                        if (fill && (fill.includes('00C851') || fill.includes('green'))) {
                                            el.setAttribute('fill', '#FF4444');
                                            colorChanged = true;
                                        }
                                    });
                                    if (colorChanged) {
                                        console.log('强制修正了K线图颜色');
                                    }
                                }
                            } catch (e) {
                                console.log('持续监控颜色失败:', e);
                            }
                        }, 500);
                        
                        // 5秒后停止监控
                        setTimeout(() => {
                            clearInterval(colorMonitor);
                        }, 5000);
                        

                    } catch (error) {
                        console.error('渲染K线图表时出错:', error);
                        this.showMessage('图表渲染失败: ' + error.message, 'error');
                    }
                },
                
                addTechnicalIndicators() {
                    if (!this.klineChart) return;
                    
                    try {
                        // 尝试使用不同的方法名称
                        const methods = [
                            'addTechnicalIndicator',
                            'createTechnicalIndicator',
                            'addIndicator',
                            'createIndicator'
                        ];
                        
                        let methodFound = false;
                        
                        for (const method of methods) {
                            if (typeof this.klineChart[method] === 'function') {
                                console.log(`使用 ${method} 方法`);
                                
                                // 添加移动平均线
                    if (this.showMA5) {
                                    try {
                                        this.klineChart[method]('MA', { 
                                            calcParams: [5],
                                            styles: {
                                                lines: [{
                                                    color: '#FF9800',
                                                    size: 1
                                                }]
                                            }
                                        });
                                    } catch (error) {
                                        console.log(`MA5 添加失败 (${method}):`, error);
                                    }
                    }
                    
                    if (this.showMA10) {
                                    try {
                                        this.klineChart[method]('MA', { 
                                            calcParams: [10],
                                            styles: {
                                                lines: [{
                                                    color: '#4CAF50',
                                                    size: 1
                                                }]
                                            }
                                        });
                                    } catch (error) {
                                        console.log(`MA10 添加失败 (${method}):`, error);
                                    }
                    }
                    
                    if (this.showMA20) {
                                    try {
                                        this.klineChart[method]('MA', { 
                                            calcParams: [20],
                                            styles: {
                                                lines: [{
                                                    color: '#9C27B0',
                                                    size: 1
                                                }]
                                            }
                                        });
                                    } catch (error) {
                                        console.log(`MA20 添加失败 (${method}):`, error);
                                    }
                                }
                                
                                methodFound = true;
                                break;
                            }
                        }
                        
                        if (!methodFound) {
                            console.log('未找到可用的技术指标方法');
                        }

                    } catch (error) {
                        console.error('添加技术指标时出错:', error);
                    }
                },
                
                addSupportResistanceLevels() {
                    if (!this.klineChart || !this.supportResistanceLevels) return;
                    
                    try {
                        // 尝试使用不同的方法名称
                        const methods = [
                            'addOverlay',
                            'createOverlay',
                            'addShape',
                            'createShape',
                            'addAnnotation',
                            'createAnnotation'
                        ];
                        
                        let methodFound = false;
                        
                        for (const method of methods) {
                            if (typeof this.klineChart[method] === 'function') {
                                console.log(`使用 ${method} 方法添加支撑压力位`);
                                
                                const levels = this.supportResistanceLevels;
                                const firstTimestamp = new Date(this.stockData[0].date).getTime();
                                const lastTimestamp = new Date(this.stockData[this.stockData.length - 1].date).getTime();
                                
                                // 添加支撑位
                         levels.support.forEach((level, index) => {
                                    try {
                                        this.klineChart[method]({
                                            name: 'horizontalRayLine',
                                            points: [
                                                { timestamp: firstTimestamp, price: level.price },
                                                { timestamp: lastTimestamp, price: level.price }
                                            ],
                                            styles: {
                                                color: '#4CAF50',
                                                lineWidth: 2,
                                                lineDash: [5, 5]
                                            }
                                        });
                                    } catch (error) {
                                        console.log(`支撑位添加失败 (${method}):`, error);
                                    }
                                });
                                
                                // 添加压力位
                         levels.resistance.forEach((level, index) => {
                                    try {
                                        this.klineChart[method]({
                                            name: 'horizontalRayLine',
                                            points: [
                                                { timestamp: firstTimestamp, price: level.price },
                                                { timestamp: lastTimestamp, price: level.price }
                                            ],
                                            styles: {
                                                color: '#F44336',
                                                lineWidth: 2,
                                                lineDash: [5, 5]
                                            }
                                        });
                                    } catch (error) {
                                        console.log(`压力位添加失败 (${method}):`, error);
                                    }
                                });
                                
                                methodFound = true;
                                break;
                            }
                        }
                        
                        if (!methodFound) {
                            console.log('未找到可用的支撑压力位方法');
                        }

                    } catch (error) {
                        console.error('添加支撑压力位时出错:', error);
                    }
                },
                
                renderVolumeChart() {
                    if (typeof window.klinecharts === 'undefined') {
                        console.error('klinecharts 未定义，无法渲染成交量图表');
                        return;
                    }
                    
                    const container = document.getElementById('volumeChart');
                    if (!container) {
                        console.error('成交量图表容器未找到');
                        return;
                    }
                    
                    try {
                        // 销毁之前的图表
                        if (this.volumeChart) {
                            const disposeMethods = [
                                'dispose',
                                'destroy',
                                'remove',
                                'clear',
                                'reset'
                            ];
                            
                            let disposeMethodFound = false;
                            
                            for (const method of disposeMethods) {
                                if (typeof this.volumeChart[method] === 'function') {
                                    try {
                                        this.volumeChart[method]();
                                        console.log(`使用 ${method} 方法销毁成交量图表`);
                                        disposeMethodFound = true;
                                        break;
                                    } catch (error) {
                                        console.log(`销毁成交量图表失败 (${method}):`, error);
                                    }
                                }
                            }
                            
                            if (!disposeMethodFound) {
                                console.log('未找到可用的销毁方法，跳过销毁');
                            }
                        }
                        
                        // 创建成交量图表，并传入A股颜色配置
                        const volumeChartOptions = {
                            styles: {
                                volume: {
                                    up: {
                                        color: '#FF4444'      // 上涨成交量颜色（红色）
                                    },
                                    down: {
                                        color: '#00C851'      // 下跌成交量颜色（绿色）
                                    },
                                    noChange: {
                                        color: '#999999'      // 平盘成交量颜色（灰色）
                                    }
                                }
                            }
                        };
                        this.volumeChart = window.klinecharts.init(container, volumeChartOptions);
                        
                        // 转换数据格式为K线格式（包含成交量）
                        const volumeData = this.stockData.map(item => {
                            const close = parseFloat(item.close) || 0;
                            const open = parseFloat(item.open) || 0;
                            const volume = parseFloat(item.volume) || 0;
                            
                            // 计算涨跌，用于成交量颜色判断
                            const isUp = close > open;
                            const isDown = close < open;
                            
                            return {
                                timestamp: new Date(item.date).getTime(),
                                open: open,
                                high: parseFloat(item.high) || 0,
                                low: parseFloat(item.low) || 0,
                                close: close,
                                volume: volume,
                                // 添加涨跌标记，用于成交量颜色显示
                                isUp: isUp,
                                isDown: isDown
                            };
                        });
                        
                        // 设置数据
                        this.volumeChart.applyNewData(volumeData);
                        
                        // 添加成交量指标
                        const volumeMethods = [
                            'addTechnicalIndicator',
                            'createTechnicalIndicator',
                            'addIndicator',
                            'createIndicator'
                        ];
                        
                        let volumeMethodFound = false;
                        
                        for (const method of volumeMethods) {
                            if (typeof this.volumeChart[method] === 'function') {
                                try {
                                    this.volumeChart[method]('VOL');
                                    console.log(`成交量指标使用 ${method} 方法成功`);
                                    volumeMethodFound = true;
                                    break;
                        } catch (error) {
                                    console.log(`成交量指标添加失败 (${method}):`, error);
                                }
                            }
                        }
                        
                        if (!volumeMethodFound) {
                            console.log('未找到可用的成交量指标方法');
                        }
                        
                        // 设置成交量图表样式 - A股习惯：红涨绿跌
                        try {
                            // 方法1：使用setStyles
                            this.volumeChart.setStyles({
                                grid: {
                                    show: true,
                                    horizontal: {
                                        show: true,
                                        color: '#EDEDED',
                                        size: 1
                                    }
                                },
                                candle: {
                                    show: false // 隐藏K线，只显示成交量
                                },
                                // 成交量柱状图颜色设置 - 使用正确的属性名
                                volume: {
                                    up: {
                                        color: '#FF4444'      // 上涨成交量颜色（红色）
                                    },
                                    down: {
                                        color: '#00C851'      // 下跌成交量颜色（绿色）
                                    },
                                    noChange: {
                                        color: '#999999'      // 平盘成交量颜色（灰色）
                                    }
                                }
                            });
                        } catch (e) {
                            console.log('成交量setStyles方法失败:', e);
                        }
                        
                        // 方法2：尝试使用其他可能的配置方法
                        try {
                            if (this.volumeChart.updateStyles) {
                                this.volumeChart.updateStyles({
                                    volume: {
                                        up: { color: '#FF4444' },
                                        down: { color: '#00C851' },
                                        noChange: { color: '#999999' }
                                    }
                                });
                            }
                        } catch (e) {
                            console.log('成交量updateStyles方法失败:', e);
                        }
                        
                        // 方法3：强制设置成交量DOM元素的颜色
                        setTimeout(() => {
                            try {
                                const volumeContainer = document.getElementById('volumeChart');
                                if (volumeContainer) {
                                    const svgElements = volumeContainer.querySelectorAll('svg rect, svg path');
                                    svgElements.forEach(el => {
                                        const fill = el.getAttribute('fill');
                                        if (fill && fill.includes('00C851')) {
                                            el.setAttribute('fill', '#FF4444');
                                        }
                                    });
                                }
                            } catch (e) {
                                console.log('强制设置成交量DOM颜色失败:', e);
                            }
                        }, 1000);
                        
                        // 方法4：持续监控和强制设置成交量颜色（每500ms检查一次）
                        const volumeColorMonitor = setInterval(() => {
                            try {
                                const volumeContainer = document.getElementById('volumeChart');
                                if (volumeContainer) {
                                    let colorChanged = false;
                                    const svgElements = volumeContainer.querySelectorAll('svg rect, svg path');
                                    svgElements.forEach(el => {
                                        const fill = el.getAttribute('fill');
                                        if (fill && (fill.includes('00C851') || fill.includes('green'))) {
                                            el.setAttribute('fill', '#FF4444');
                                            colorChanged = true;
                                        }
                                    });
                                    if (colorChanged) {
                                        console.log('强制修正了成交量颜色');
                                    }
                                }
                            } catch (e) {
                                console.log('持续监控成交量颜色失败:', e);
                            }
                        }, 500);
                        
                        // 5秒后停止监控
                        setTimeout(() => {
                            clearInterval(volumeColorMonitor);
                        }, 5000);
                        

                    } catch (error) {
                        console.error('渲染成交量图表时出错:', error);
                    }
                },
                
                updateChart() {
                    try {
                        if (this.klineChart) {
                            // 清除所有技术指标
                            const clearMethods = [
                                'removeAllTechnicalIndicators',
                                'clearTechnicalIndicators',
                                'removeAllIndicators',
                                'clearIndicators',
                                'removeTechnicalIndicator',
                                'clearTechnicalIndicator'
                            ];
                            
                            let clearMethodFound = false;
                            
                            for (const method of clearMethods) {
                                if (typeof this.klineChart[method] === 'function') {
                                    try {
                                        this.klineChart[method]();
                                        console.log(`使用 ${method} 方法清除技术指标`);
                                        clearMethodFound = true;
                                        break;
                                    } catch (error) {
                                        console.log(`清除技术指标失败 (${method}):`, error);
                                    }
                                }
                            }
                            
                            if (!clearMethodFound) {
                                console.log('未找到可用的清除技术指标方法，跳过清除');
                            }
                            
                            // 重新添加技术指标
                            this.addTechnicalIndicators();
                            
                            // 重新添加支撑位和压力位
                            if (this.showSupportResistance) {
                                this.addSupportResistanceLevels();
                            }
                        }
                        
                        if (this.showVolume && this.stockData.length > 0) {
                            this.renderVolumeChart();
                        } else if (this.volumeChart) {
                            this.volumeChart.dispose();
                            this.volumeChart = null;
                        }
                        

                    } catch (error) {
                        console.error('更新图表时出错:', error);
                        this.showMessage('图表更新失败: ' + error.message, 'error');
                    }
                },
                
                // 计算支撑位和压力位
                calculateSupportResistance() {
                    if (this.stockData.length < 20) {
                        return { support: [], resistance: [] };
                    }
                    
                    const prices = this.stockData.map(item => parseFloat(item.close) || 0);
                    const highs = this.stockData.map(item => parseFloat(item.high) || 0);
                    const lows = this.stockData.map(item => parseFloat(item.low) || 0);
                    
                    // 寻找局部最高点和最低点
                    const peaks = [];
                    const troughs = [];
                    
                    // 使用滑动窗口寻找峰值和谷值
                    const windowSize = 5;
                    for (let i = windowSize; i < prices.length - windowSize; i++) {
                        const current = prices[i];
                        const leftWindow = prices.slice(i - windowSize, i);
                        const rightWindow = prices.slice(i + 1, i + windowSize + 1);
                        
                        // 检查是否为局部最高点
                        if (current > Math.max(...leftWindow) && current > Math.max(...rightWindow)) {
                            peaks.push({
                                index: i,
                                price: current,
                                date: this.stockData[i].date
                            });
                        }
                        
                        // 检查是否为局部最低点
                        if (current < Math.min(...leftWindow) && current < Math.min(...rightWindow)) {
                            troughs.push({
                                index: i,
                                price: current,
                                date: this.stockData[i].date
                            });
                        }
                    }
                    
                    // 聚类相似的价格水平
                    const clusterThreshold = 0.02; // 2%的价格差异阈值
                    
                    // 聚类压力位（阻力位）
                    const resistanceLevels = this.clusterPriceLevels(peaks, clusterThreshold, 'resistance');
                    
                    // 聚类支撑位
                    const supportLevels = this.clusterPriceLevels(troughs, clusterThreshold, 'support');
                    
                    return {
                        support: supportLevels,
                        resistance: resistanceLevels
                    };
                },
                
                // 聚类价格水平
                clusterPriceLevels(points, threshold, type) {
                    if (points.length === 0) return [];
                    
                    const clusters = [];
                    const sortedPoints = [...points].sort((a, b) => a.price - b.price);
                    
                    let currentCluster = [sortedPoints[0]];
                    
                    for (let i = 1; i < sortedPoints.length; i++) {
                        const current = sortedPoints[i];
                        const clusterAvg = currentCluster.reduce((sum, p) => sum + p.price, 0) / currentCluster.length;
                        
                        if (Math.abs(current.price - clusterAvg) / clusterAvg <= threshold) {
                            currentCluster.push(current);
                        } else {
                            // 完成当前聚类
                            if (currentCluster.length >= 2) {
                                const avgPrice = currentCluster.reduce((sum, p) => sum + p.price, 0) / currentCluster.length;
                                const strength = currentCluster.length;
                                clusters.push({
                                    price: avgPrice,
                                    strength: strength,
                                    points: currentCluster,
                                    type: type
                                });
                            }
                            currentCluster = [current];
                        }
                    }
                    
                    // 处理最后一个聚类
                    if (currentCluster.length >= 2) {
                        const avgPrice = currentCluster.reduce((sum, p) => sum + p.price, 0) / currentCluster.length;
                        const strength = currentCluster.length;
                        clusters.push({
                            price: avgPrice,
                            strength: strength,
                            points: currentCluster,
                            type: type
                        });
                    }
                    
                    // 按强度排序，返回前3个最强的水平
                    return clusters
                        .sort((a, b) => b.strength - a.strength)
                        .slice(0, 3);
                },
                
                showMessage(text, type = 'success') {
                    this.message = text;
                    this.messageType = type;
                    setTimeout(() => {
                        this.message = '';
                    }, 5000);
                },
                
                getStatusIcon() {
                    switch (this.messageType) {
                        case 'success':
                            return 'fas fa-check-circle';
                        case 'warning':
                            return 'fas fa-exclamation-triangle';
                        case 'error':
                            return 'fas fa-times-circle';
                        default:
                            return 'fas fa-info-circle';
                    }
                }
            }
        }).mount('#app');
    </script>
</body>
</html>


